from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView

from recommand_demo.serializers import BehaviorSerializer
from movie.models import Behavior


class BehaviorApiView(APIView):
    # def get(self,request):
    #     behavior_list = Behavior.objects.all()
    #     serializer = BehaviorSerializer(instance=behavior_list,many=True)
    #     result = {
    #         'data': serializer.data,
    #         'code': 2000,
    #         'msg': '获取成功'
    #     }
    #     return Response(result)
    def post(self, request):
        print(request.data)
        try:
            movie_id = request.data.get('movie')
            user_id = request.data.get('user')
            behavior_like = request.data.get('behavior_like')
            behavior_score = request.data.get('behavior_score')
            behavior_list = Behavior.objects.filter(user_id=user_id, movie_id=movie_id).first()
            if behavior_list == None:
                Behavior.objects.create(user_id=user_id, movie_id=movie_id, behavior_like=behavior_like,
                                        behavior_score=behavior_score)
            else:
                # 如果存在，则更新对应的字段（只更新有值的字段）
                if behavior_like is not None:
                    behavior_list.behavior_like = behavior_like
                if behavior_score is not None:
                    behavior_list.behavior_score = behavior_score
                behavior_list.save()  # 保存更改
        except Exception:
            return Response({'code': 4000, 'msg': '接口处理失败'}, status=400)

        result = {
            # 'data': serializer.data,
            'code': 2000,
            'msg': '评分成功'
        }
        return Response(result)
